package org.smartopen.unionpay.openapi.aspect;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.smartframework.unionpay.domain.request.SmartPayBaseRequest;
import org.smartframework.unionpay.domain.request.SmartPayRefundRequest;
import org.smartframework.unionpay.domain.request.SmartPayUnifiedorderRequest;
import org.smartopen.unionpay.openapi.component.UnionPayOpenApiProperties;

import java.util.Arrays;

/**
 * 字典AOP
 *
 * @author ycc
 * @date 2021-07-21
 */
@Aspect
@Slf4j
@RequiredArgsConstructor
public class OpenApiAspect {

    private final UnionPayOpenApiProperties properties;

    @Before("execution(* org.smartopen.unionpay.openapi.service.feigin..*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {

        // 调用下一个advice或者执行目标方法，返回值为目标方法返回值，因此可以通过更改返回值，修改方法的返回值
        // 如：修改obj，然后将obj返回
        // 获取当前方法对象
        //request设置缺省值
        Arrays.stream(joinPoint.getArgs())
                .filter(v -> v instanceof SmartPayBaseRequest)
                .map(v -> (SmartPayBaseRequest) v)
                .forEach(req -> {
                    this.autoRequest(req);
                });
    }

    private void autoRequest(SmartPayBaseRequest request) {
        if (StrUtil.isEmpty(request.getOrgId())) {
            request.setOrgId(properties.getOrgId());
        }
        if (StrUtil.isEmpty(request.getMchId())) {
            request.setMchId(properties.getMchId());
        }
        if(request instanceof SmartPayUnifiedorderRequest){
            SmartPayUnifiedorderRequest req = (SmartPayUnifiedorderRequest)request;
            if (StrUtil.isEmpty(req.getNotifyUrl())) {
                req.setNotifyUrl(properties.getNotifyUrl());
            }
        }else if(request instanceof SmartPayRefundRequest){
            SmartPayRefundRequest req = (SmartPayRefundRequest)request;
            if (StrUtil.isEmpty(req.getNotifyUrl())) {
                req.setNotifyUrl(properties.getRefundNotifyUrl());
            }
        }
    }
}